import { computed, reactive, watch } from 'vue'
import { defineStore } from 'pinia'
import { ROULETTE_DATA_PREFIX, SUFFIX_JSON } from "@/data/constants/Constants";
import { LogList } from "@/data/entity/LogList";
import { useRouletteDataStore } from "@/data/stores/rouletteData";
import { useAccountStore } from "@/data/stores/account";
import { Log } from "@/data/entity/Log";
import * as localStorage from "@/data/persistent/localStorage";
import * as gitee from '@/data/persistent/gitee'

export const useLogListStore = defineStore('logList', ()=>{
    const logList = reactive(LogList.parse(localStorage.get(ROULETTE_DATA_PREFIX + useRouletteDataStore().rouletteData)))
    const index = computed(()=>{
        let index = 0
        logList.data.forEach(log => {
            if (log.count > index){
                index = log.count
            }
        })
        return index
    })

    function getLength(){
        return logList.data.length
    }
    function addLogList(_logList:Log[]) {
        console.log(_logList)
        logList.data.push(..._logList)
        sort()
    }

    function delLogList(name:string){
        localStorage.del(ROULETTE_DATA_PREFIX + name)
    }

    function getLogList(start:number, limit:number):Log[]{
        return logList.data.slice(start, start + limit)
    }

    function getReverseLogList(start:number, limit:number):Log[]{
        return logList.data.slice(
            logList.data.length - 1 - start - limit > 0 ? logList.data.length - 1 - start - limit : 0
            , logList.data.length - start
        ).reverse()
    }

    function addLog(log:Log) {
        logList.data.push(log)
    }

    function updateLog(oldLog:Log, newLog:Log) {
        const index = logList.data.indexOf(oldLog)
        logList.data.splice(index, 1, Log.parse(newLog))
    }

    function deleteLog(log:Log) {
        const index = logList.data.indexOf(log)
        logList.data.splice(index, 1)
    }

    function sort(){
        logList.data.sort((a, b) => {
            return a.count <= b.count ? -1:1
        })
    }

    function save2Gitee(){
        gitee.set(useRouletteDataStore().rouletteData + SUFFIX_JSON, logList)
    }

    function reset(){
        logList.data = LogList.parse(localStorage.get(ROULETTE_DATA_PREFIX + useRouletteDataStore().rouletteData)).data
    }

    watch(
        logList,
        async (logList) => {
            localStorage.set(ROULETTE_DATA_PREFIX + useRouletteDataStore().rouletteData, logList)
            if (useAccountStore().getGitee().auto_save){
                save2Gitee()
            }
    })

    return { index, logList, getLength, getLogList, getReverseLogList, addLogList, delLogList, addLog, updateLog, deleteLog, sort, save2Gitee, reset }
})
